import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.Scanner;

public class talkClient {

    private final String host;
    private final Integer port;

    public talkClient(String host, Integer port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        NioEventLoopGroup clientEventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(clientEventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("decoder",new StringDecoder());
                            pipeline.addLast("encoder",new StringEncoder());
                            pipeline.addLast(new talkClientHandler());
                        }
                    });
            //绑定主机和端口
            ChannelFuture channelFuture = bootstrap.connect(host,port).sync();

            //添加监听器
            channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    if (channelFuture.isSuccess()){
                        System.out.println("client is startting...");
                    }else if (channelFuture.isDone()){
                        System.out.println("client is start success...");
                    }
                }
            });

            Channel channel = channelFuture.channel();
            System.out.println("----------"+channel.localAddress()+"-----------");

            //创建扫描器
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()){
                String msg = scanner.nextLine();
                //将控制台上的数据写入到channel中
                channel.writeAndFlush(msg+"\r\n");
            }

            //监听关闭通道
            channelFuture.channel().closeFuture().sync();
            scanner.close();
        }finally {
            clientEventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new talkClient("127.0.0.1",9999).run();
    }
}
